package com.software.loginregister.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.software.loginregister.R;
import java.util.ArrayList;

public class MapLocationActivity extends AppCompatActivity {
    private static final String TAG = "MapLocationActivity";
    private static final int PERMISSION_REQUEST_CODE = 1001;
    private TextView tvLocation;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: 开始初始化活动");
        setContentView(R.layout.activity_map_location);
        initViews();
        initMap();
        // 检查是否需要动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPermissions();
        } else {
            requestLocation();
        }
    }
    private void initMap() {
        try {
            mMapView = findViewById(R.id.map_container);
            if (mMapView == null) {
                Log.e(TAG, "initMap: MapView未找到，请检查布局文件");
                return;
            }

            mBaiduMap = mMapView.getMap();
            if (mBaiduMap == null) {
                Log.e(TAG, "initMap: BaiduMap获取失败");
                return;
            }

            // 设置地图缩放级别
            MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0F);
            mBaiduMap.setMapStatus(msu);

            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
        } catch (Exception e) {
            Log.e(TAG, "initMap: 初始化失败", e);
        }
    }

    private void requestLocation() {
        LocationClient.setAgreePrivacy(true);
        try {
            mLocationClient = new LocationClient(this);

            LocationClientOption option = new LocationClientOption();
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
            option.setCoorType("bd09ll");
            option.setFirstLocType(LocationClientOption.FirstLocType.ACCURACY_IN_FIRST_LOC);
            option.setScanSpan(1000);
            option.setOpenGps(true);
            option.setLocationNotify(true);
            option.setIgnoreKillProcess(false);
            option.SetIgnoreCacheException(false);
            option.setWifiCacheTimeOut(5 * 60 * 1000);
            option.setEnableSimulateGnss(false);
            option.setNeedNewVersionRgc(true);
            option.setIsNeedAddress(true);

            mLocationClient.setLocOption(option);

            mLocationClient.registerLocationListener(new BDLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation location) {
                    if (location == null || mMapView == null) {
                        return;
                    }

                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    Log.i(TAG, "onReceiveLocation: latitude:" + latitude + " longitude:" + longitude);

                    MyLocationData locationData = new MyLocationData.Builder()
                            .accuracy(location.getRadius())
                            .direction(location.getDirection())
                            .latitude(latitude)
                            .longitude(longitude)
                            .build();

                    mBaiduMap.setMyLocationData(locationData);

                    // 更新位置文本
                    String locationStr = location.getCity() + "·" + location.getDistrict();
                    tvLocation.setText(locationStr);

                    // 移动地图到定位点
                    LatLng ll = new LatLng(latitude, longitude);
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                    mBaiduMap.animateMapStatus(u);
                }
            });

            // 设置定位图层的配置
            MyLocationConfiguration configuration = new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.COMPASS,
                    true,
                    null
            );
            mBaiduMap.setMyLocationConfiguration(configuration);

            // 开始定位
            mLocationClient.start();
            Log.d(TAG, "requestLocation: 开始定位");

        } catch (Exception e) {
            Log.e(TAG, "requestLocation: 初始化定位失败", e);
            Toast.makeText(this, "定位服务初始化失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void initViews() {
        tvLocation = findViewById(R.id.tv_map_location);

        // 设置返回按钮
        findViewById(R.id.iv_location_back).setOnClickListener(v -> finish());

        // 设置确认按钮
        findViewById(R.id.btn_map_confirm).setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("location", tvLocation.getText().toString());
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                requestLocation();
            } else {
                Toast.makeText(this, "需要定位权限才能使用此功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: MapView状态: " + (mMapView != null ? "已初始化" : "未初始化"));
        if (mMapView != null) {
            mMapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: MapView状态: " + (mMapView != null ? "已初始化" : "未初始化"));
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy: 开始清理资源");
        if (mLocationClient != null) {
            mLocationClient.stop();
            Log.d(TAG, "onDestroy: LocationClient已停止");
        }
        if (mBaiduMap != null) {
            mBaiduMap.setMyLocationEnabled(false);
            Log.d(TAG, "onDestroy: 定位图层已关闭");
        }
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
            Log.d(TAG, "onDestroy: MapView已销毁");
        }
        super.onDestroy();
    }

    private void checkPermissions() {
        String[] permissions = {
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        };

        ArrayList<String> toApplyList = new ArrayList<>();
        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
            }
        }

        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    toApplyList.toArray(new String[0]),
                    PERMISSION_REQUEST_CODE);
        } else {
            requestLocation();
        }
    }
}